import time

###############################
class LogReader():


    def __init__(self):
        
        self.data = None
        self.fileid = 0
        self.filelist = []

    def set_file(self, fn):
        self.f = open(fn,'r')
    
    def set_fileid(self):
        print self.filelist[self.fileid]
        self.f = open(self.filelist[self.fileid],'r')

    def read_data(self):
        try:
            datastr = self.f.next()
        except StopIteration:
            return False
        self.data = json.loads(datastr)
        return True
    
    def read_wifi(self):
        w = WifiLog(self.data['wifi'])
        return w.get_mac()
        
    def read_cell(self):
        c = CellLog(self.data['cell'])
        cellid = c.get_global_id()
        return cellid

    def gettime(self):
        a = self.data['cell']
        return time.ctime(int(a['t']))
        
    def test(self):
        if deli[0] == True:
            c = data["cell"]
            cellid = str(c['lac']) + str(c['cid'])
            self.readings['cell'].append(cellid)
            print c['t']
        else:
            self.readings['cell'].append(None)

        if deli[1] == True:
            a = data['acc']
            coords = []
            for i in a:
                coords.extend(i)
            re = self.ismove(coords)
            self.readings['acc'].append(re)
        else:
            self.readings['acc'].append(None)

        if deli[2] == True:
            g = data['gps']
            self.readings['gps'].append(g)
        else:
            self.readings['gps'].append(None)

        if deli[3] == True:
            w = data['wifi']
            wlist = w.keys()
            wlist.remove('t')
            self.readings['wifi'].append(wlist)
        else:
            self.readings['wifi'].append(None)
    


    def reset(self):
        self.readings = {'cell':[],'acc':[],'gps':[],'wifi':[]}

    def scan_dir(self,dirname,pattern):
        self.filelist = []
        for root, dirs, files in os.walk(dirname):
            for fname in files:
                if pattern.match(fname):
                    filename = root+"/"+fname
                    self.filelist.append(filename)

        self.filelist = sorted(self.filelist)
        self.fileid = 0

    def nextfile(self):
        if self.fileid < len(self.filelist)-1:
            self.fileid += 1
            return True
        else:
            return False

    def prevfile(self):
        if self.fileid >0:
            self.fileid -= 1
            return True
        else:
            return False

#################################
#
#################################
class WifiLog():
    

    def __init__(self,dat):
        self.data = dat

    def get_mac(self):
        wlist = self.data.keys()
        if 't' in wlist:
            wlist.remove('t')
        return wlist

    
#################################
#
#################################
class AccLog():


    def __init__(self):
        self.accum = 0 

    def ismove(self,accs):

        x1=None
        y1=None
        z1=None
        sumx = 0
        sumy = 0
        sumz = 0
        for coord in accs:
            x = int(coord[0])
            y = int(coord[1])
            z = int(coord[2])
            if x1!=None and y1!= None and z1!= None:
                sumx = sumx + abs(x1-x)
                sumy = sumy + abs(y1-y)
                sumz = sumz + abs(z1-z) 
            x1=x
            y1=y
            z1=z
        samples = len(accs)
        ave = (sumx/samples+sumy/samples+sumz/samples)/3
        #print ave
        if ave > 15 and self.accum > 0:
            self.accum -= 1
        if ave <= 15 and self.accum <6:
            self.accum += 1
        if ave > 15 and self.accum <= 4:
            return True
        elif ave <= 15 and self.accum >=6:
            return False


#################################
#
#################################
import os
import platform

if platform.machine().startswith('arm'):
    import simplejson as json
else:
    import json

class CellLog():
    

    def __init__(self,dat):
        self.data = dat
        self.fn = './global_cell_id.json'
        if os.path.exists(self.fn):
            f = open(self.fn,'r')
            self.global_ids = json.load(f)
            f.close()
        else:
            self.global_ids = {}

    def get_global_id(self):
        cidstr = str(self.data['mcc'])+"."+str(self.data['mnc']) + "."
        cidstr += str(self.data['lac'])+"."+str(self.data['cid'])
        if cidstr in self.global_ids:
            return self.global_ids[cidstr]
        else:
            newid = len(self.global_ids)
            self.global_ids[cidstr] = newid
            f = open(self.fn,'w')
            json.dump(self.global_ids,f)
            f.close()
            return newid



